export default {
  namespaced: true, // 开启命名空间 modules才会生效
  state: {
    shoplist: [ // 商品数据
      {
        id: 1,
        name: '鱼香肉丝',
        price: 10
      },
      {
        id: 2,
        name: '宫保鸡丁',
        price: 20
      },
      {
        id: 3,
        name: '土豆丝',
        price: 15
      },
      {
        id: 4,
        name: '米饭',
        price: 2
      }
    ],
    addcart: [] // 添加到购物车的数据
  },
  getters: {
    shoplist: state => state.shoplist, // 商品数据
    cartlist: state => { // 购物车数据
      return state.addcart.map(({ id, num }) => {
        const index = state.shoplist.find(n => n.id === id)
        return {
          ...index,
          num
        }
      })
    },
    totalprice: (state, getters) => { // 计算总价
      let price = 0
      getters.cartlist.forEach(e => {
        price += e.price * e.num
      })
      return price
    },
    totalnum: (state, getters) => { // 计算数量
      let sum = 0
      getters.cartlist.forEach(e => {
        sum += e.num
      })
      return sum
    }
  },
  actions: {
    // 添加到购物车
    addtocart (Store, product) {
      Store.commit('add', product.id)
    },
    // 清空购物车
    clsall (Store) {
      Store.commit('clear')
    },
    // 删除某个商品
    delproduct (Store, obj) {
      Store.commit('delete', obj.id)
    }
  },
  mutations: {
    add (state, id) {
      const index = state.addcart.find(e => e.id === id)
      if (!index) {
        state.addcart.push({
          id: id,
          num: 1
        })
      } else {
        index.num++
      }
    },
    // 清空数组
    clear (state) {
      state.addcart = []
    },
    delete (state, val) {
      state.addcart.forEach((n, i) => {
        if (n.id === val) {
          state.addcart.splice(i, 1)
        }
      })
    }
  }
}
